package com.tdly.buduizhong.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tdly.buduizhong.R;
import com.tdly.buduizhong.base.BaseActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class SettingActivity extends BaseActivity implements View.OnClickListener {
    Context context = this;
    private RelativeLayout rl_setting_usb, rl_setting_bluetooth;
    private EditText et_default_name, et_set_eiss,et_cypl,et_cycd,et_btl;
    private TextView textView, tv_conn_usb, tv_conn_bluetooth, tv_default_name, tv_default_time;
    private Button bt_setting_ok, bt_setting_cancel;
    private RadioGroup rg_choose;
    private RadioButton rb_sn,rb_name;
    private String data=null;
    private String chooce="0";//0 sn,1 设备名
//    private ImageView iv_usb, iv_bluetooth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initView();
    }

    private void initView() {
        rl_setting_usb = findViewById(R.id.rl_setting_usb);
        rl_setting_bluetooth = findViewById(R.id.rl_setting_bluetooth);
        et_default_name = findViewById(R.id.et_default_name);
        et_set_eiss = findViewById(R.id.et_set_eiss);
        textView = findViewById(R.id.textView);
        tv_conn_usb = findViewById(R.id.tv_conn_usb);
        tv_conn_bluetooth = findViewById(R.id.tv_conn_bluetooth);
        tv_default_name = findViewById(R.id.tv_default_name);
        tv_default_time = findViewById(R.id.tv_default_time);
        bt_setting_ok = findViewById(R.id.bt_setting_ok);
        bt_setting_cancel = findViewById(R.id.bt_setting_cancel);
        et_cycd = findViewById(R.id.et_cycd);
        et_cypl = findViewById(R.id.et_cypl);
        et_btl = findViewById(R.id.et_btl);
        rg_choose=findViewById(R.id.rg_choose);
        rb_sn=findViewById(R.id.rb_sn);
        rb_name=findViewById(R.id.rb_name);

        rg_choose.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int id =group.getCheckedRadioButtonId();
                if(R.id.rb_sn==id){
                    chooce="0";
                }else {
                    chooce="1";
                }
            }
        });

        try {
            String path = Environment.getExternalStorageDirectory().getCanonicalPath() + "/setting/Setting.txt";
            data=readToString(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(data!=null&&data.length()>0){
            String[] mes = data.split(",");
            Log.e("!!!!!!!!String:",data);
            if(mes[0]!=null){
                et_cypl.setText(mes[0]);
            }
            if(mes[1]!=null) {
                et_cycd.setText(mes[1]);
            }
            if(mes[2]!=null) {
                et_btl.setText(mes[2]);
                //et_default_name.setText(mes[2]);
            }
            if(mes[3]!=null) {
                et_set_eiss.setText(mes[3]);
            }
//            if(mes.length==5&&mes[4]!=null) {
//                if(mes[4].equals("0")){
//                    rg_choose.check(R.id.rb_sn);
//                    chooce="0";
//                }else if(mes[4].equals("1")){
//                    rg_choose.check(R.id.rb_name);
//                    chooce="1";
//                }
//            }
        }


//        iv_usb = findViewById(R.id.iv_usb);
//        iv_bluetooth = findViewById(R.id.iv_bluetooth);
//
//        iv_bluetooth.setOnClickListener(this);
//        iv_usb.setOnClickListener(this);
        bt_setting_ok.setOnClickListener(this);
        bt_setting_cancel.setOnClickListener(this);

    }


    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_setting_ok:
                String cypl=et_cypl.getText().toString().trim();
                String cycd=et_cycd.getText().toString().trim();
                String btl=et_btl.getText().toString().trim();
//                String name=et_default_name.getText().toString().trim();
                String end=et_set_eiss.getText().toString().trim();
                if(cypl==null||cypl.length()==0||cycd==null||cycd.length()==0||btl==null||btl.length()==0||end==null||end.length()==0){
                    Toast.makeText(this,"内容不能为空",Toast.LENGTH_SHORT).show();
                    break;
                }
                try {
                    savaFileToSD();
                    Toast.makeText(this,"设置成功",Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    Toast.makeText(this,"设置失败",Toast.LENGTH_SHORT).show();
                }
                Intent intent1=new  Intent(SettingActivity.this, HomeActivity.class);
                //标识列 + Intent
                setResult(20, intent1);

                finish();
                break;
            case R.id.bt_setting_cancel:
                finish();
                break;
        }
    }




    public String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }



    //往SD卡写入文件的方法
    public void savaFileToSD() throws Exception {
        String cypl=et_cypl.getText().toString().trim();
        String cycd=et_cycd.getText().toString().trim();
        String btl=et_btl.getText().toString().trim();
        //String name=et_default_name.getText().toString().trim().replace("：",":").toUpperCase();
        String end=et_set_eiss.getText().toString().trim();
        String filecontent=cypl+","+cycd+","+btl+","+end;


        //如果手机已插入sd卡,且app具有读写sd卡的权限
        File Folder = new File(Environment.getExternalStorageDirectory().getCanonicalPath(), "setting");
        if (!Folder.exists())//判断文件夹是否存在，不存在则创建文件夹，已经存在则跳过
        {

            Folder.mkdir();//创建文件夹

            //两种方式判断文件夹是否创建成功
            //Folder.isDirectory()返回True表示文件路径是对的，即文件创建成功，false则相反
            boolean isFilemaked1 = Folder.isDirectory();
            //Folder.mkdirs()返回true即文件创建成功，false则相反
            boolean isFilemaked2 = Folder.mkdirs();

            if (isFilemaked1 || isFilemaked2) {
                Log.i("123123","创建文件夹成功");
            } else {
                Log.i("123123","创建文件夹失败");
            }

        }else {
            Log.i("123123","文件夹已存在");
        }
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/setting/" + "Setting.txt";
            Log.e("!@#!@#!$",filename);
            //这里就不要用openFileOutput了,那个是往手机内存中写数据的
            FileOutputStream output = new FileOutputStream(filename);
            output.write(filecontent.getBytes());
            //将String字符串以字节流的形式写入到输出流中
            output.close();
            //关闭输出流
        } else {
            Toast.makeText(context, "SD卡不存在或者不可读写", Toast.LENGTH_SHORT).show();
        }
    }
}